package com.sinosoft.gateway.notice;

import com.sinosoft.gateway.model.RequestMessage;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class NoticeQueue {

    private final List<SseEmitter> emitters = new ArrayList<>();

    public void addEmitter(SseEmitter emitter){
        emitters.add(emitter);
    }

    public void removeEmitter(SseEmitter emitter){
        emitters.remove(emitter);
    }

    public void publish(RequestMessage requestMessage){
        emitters.forEach((SseEmitter emitter) -> {
            try {
                emitter.send(requestMessage, MediaType.APPLICATION_JSON);
            } catch (IOException e) {
                emitter.complete();
                emitters.remove(emitter);
                e.printStackTrace();
            }
        });
    }
}
